package com.flink.window;

import com.flink.func.WaterSensorMapFunction;
import com.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

/**
 * WindowReduceDemo
 *
 * @author caizhiyang
 * @since 2024-02-26
 */
public class WindowReduceDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.socketTextStream("localhost", 7777)
                //转换成WaterSensor
                .map(new WaterSensorMapFunction())
                //按键分组
                .keyBy(w -> w.getId())
                //设置滚动窗口,窗口大小为10秒
                .window(TumblingProcessingTimeWindows.of(Time.seconds(10)))
                //设置聚合操作
                .reduce(new ReduceFunction<WaterSensor>() {
                    @Override
                    public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {
                        System.out.println("调用reduce方法，之前的结果:"+value1 + ",现在来的数据:"+value2);
                        return new WaterSensor(value1.getId(), System.currentTimeMillis(),value1.getVc()+value2.getVc());
                    }
                }).print();

        env.execute();
    }
}
